use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("cargo:rerun-if-changed=tests/generate_tile_connection_array_cases.py");

    let status = Command::new("python3")
        .arg("tests/generate_tile_connection_array_cases.py")
        .status()
        .expect("failed to execute Python script generate_tile_connection_array_cases.py");

    if !status.success() {
        panic!("failed to execute Python script generate_tile_connection_array_cases.py");
    }

    // Code generation for slot_grid
    println!("cargo:rerun-if-changed=src/tiling/neighbor_associations_match_generation.py");
    let out_dir = env::var("OUT_DIR")?;
    let dest_path = Path::new(&out_dir).join("neighbor_associations_match.rs");
    let mut file = File::create(&dest_path)?;

    let output = Command::new("python3")
        .arg("src/tiling/neighbor_associations_match_generation.py")
        .output()
        .expect("failed to execute Python script neighbor_associations_match_generation.py");

    if !output.status.success() {
        println!("script output:\n{}", String::from_utf8_lossy(&output.stderr));
        panic!("failed to execute Python script neighbor_associations_match_generation.py");
    }
    file.write_all(output.stdout.as_slice())?;
    Ok(())
}
